<?php

namespace app\models;

use app\components\BaseActiveRecord;
use Yii;
use yii\caching\TagDependency;
use yii\db\Exception;

/**
 * This is the model class for table "{{%search_history}}".
 *
 * @property int $id
 * @property string $search_word
 * @property int $num
 */
class SearchHistory extends BaseActiveRecord {

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%search_history}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['num'], 'integer'],
            [['search_word'], 'string', 'max' => 100],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => Yii::t('app', 'ID'),
            'search_word' => Yii::t('app', 'Search Word'),
            'num' => Yii::t('app', 'Num'),
        ];
    }

    public static function getHistory($n = 30) {
        $dependency = new TagDependency(['tags' => self::tableName()]);
        $defaults = ['斗破苍穹', '斗罗大陆2绝世唐门', '妖神记', '斗罗大陆3龙王传说', '武动乾坤', '凤逆天下'];
        $models = self::find()->cache(0, $dependency)->select('search_word as name')->limit($n)->where(['>', 'num', 2])->orderBy('num desc')->asArray()->all();
        if (empty($models)) {
            foreach ($defaults as $name) {
                $models[] = ['name' => $name];
            }
        }
        return $models;
    }

    /**
     * @param $name
     * @return array|bool
     * @throws Exception
     */
    public static function saveHistory($name) {
        /* @var $model SearchHistory */
        $model = self::find()->where(['search_word' => $name])->asArray()->one();
        if (!$model) {
            $model = new static();
            $model->search_word = $name;
            $model->num = 1;
            return $model->save();
        }
        static::updateAllCounters(['num' => 1], ['id' => $model['id']]);
        return static::retOK();
    }
}
